<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import wx from 'weixin-js-sdk'

const router = useRouter()

const route = useRoute()
const timer = ref() // 响应式定时器

const isSubmit = ref(false)
const isPaying = ref(false)

const isMobile = ref(false)

function checkDevice() {
  const userAgent = navigator.userAgent.toLowerCase()
  // 常见的手机端的 userAgent 字符串判断
  const mobileKeywords = ['iphone', 'ipod', 'android', 'windows phone', 'blackberry', 'webos']

  isMobile.value = mobileKeywords.some(keyword => userAgent.includes(keyword))
}

const msg = ref('')

const showQRCodeModal = ref(false)

async function checkOrder() {
  const oid = route.query.oid
  const { data: res } = await useFetchPost('/api/Yunshi/yunshiOrder', {
    oid,
  })
  return res
}

const name = ref('')
const price = ref(0)

async function yunshi() {
  try {
    const r = await checkOrder()
    // console.log('API响应:', r.value); // 调试用
    if (r.value.code !== 200) {
      router.push({ path: '/yunshi' })
    }
    const res = JSON.parse(r.value.data.data)
    if (res !== null) {
      name.value = res.name
      price.value = r.value.data.money
    }
    // 严格判断数据存在性（根据实际API结构调整）
    if (r.value?.data !== undefined && r.value.data !== null && r.value.data.status == 1) {
      router.push({ path: '/yunshi/result', query: { oid: route.query.oid } })
    }
    else {
      // 继续轮询
      timer.value = setTimeout(yunshi, 3000)
    }
  }
  catch (error) {
    console.error('请求失败:', error)
    // 失败后继续轮询
    timer.value = setTimeout(yunshi, 3000)
  }
}

// yunshi()
// 组件挂载时启动首次请求
onMounted(() => {
  yunshi()
  checkDevice()
})

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearTimeout(timer.value)
    timer.value = null
  }
})
const isWxConfigured = ref(false)
const userInfo = useUserInfoState()
const qrCodeUrl = ref('')

// 判断是否为微信浏览器
const isWeChat = () => /MicroMessenger/i.test(navigator.userAgent)

async function submitPayZfb() {
  if (isPaying.value)
    return
  isPaying.value = true

  try {
    let method
    if (isMobile.value && isWeChat()) {
      method = 'mp'
    }
    else if (isMobile.value) {
      method = 'wap'
    }
    else {
      method = 'web'
    }
    const oid = route.query.oid
    const { data: res } = await useFetchPost('/api/Orders/payOrder', {
      oid,
      user_id: userInfo.value.id,
      returnurl: useRequestURL().href,
      type: 'alipay',
      method,
    })

    if (!res.value || !res.value.data || !res.value.data.targetUrl) {
      msg.value = '未获取到支付信息，请稍后再试'
      isSubmit.value = true
      return
    }

    // 插入 form 并执行
    const wrapper = document.createElement('div')
    wrapper.innerHTML = res.value.data.targetUrl
    document.body.appendChild(wrapper)

    // 有些浏览器安全策略会阻止 inline script 执行，需要手动触发
    const form = wrapper.querySelector('form') as HTMLFormElement | null
    if (form) {
      form.submit()
    }
    else {
      msg.value = '支付表单解析失败'
      isSubmit.value = true
    }
  }
  catch (err) {
    console.error('支付宝支付异常:', err)
    msg.value = '请求失败，请稍后再试'
    isSubmit.value = true
  }
  finally {
    isPaying.value = false
  }
}

async function submitPayWx() {
  if (isPaying.value)
    return // 防止重复点击
  isPaying.value = true
  try {
    let method
    if (isMobile.value && isWeChat()) {
      method = 'mp'
    }
    else if (isMobile.value) {
      method = 'wap'
    }
    else {
      method = 'scan'
    }
    const oid = route.query.oid
    const { data: res } = await useFetchPost('/api/Orders/payOrder', {
      oid,
      user_id: userInfo.value.id,
      returnurl: useRequestURL().href,
      type: 'wechat',
      method,
    })
    const info = res.value.data
    if (!isWxConfigured.value) {
      wx.config({
        debug: false, // 开启调试模式，调试时为true
        appId: info.appId, // 公众号的唯一标识
        timestamp: info.timeStamp, // 时间戳
        nonceStr: info.nonceStr, // 随机串
        signature: info.paySign, // 签名
        jsApiList: ['chooseWXPay'], // 需要调用的JS接口
      })
      isWxConfigured.value = true
    }

    if (isMobile.value && isWeChat()) {
      const wxReadyTimeout = setTimeout(() => {
        msg.value = '微信支付初始化失败，请刷新页面重试'
        isSubmit.value = true
        isPaying.value = false
      }, 5000)

      wx.ready(() => {
        clearTimeout(wxReadyTimeout) // 成功准备则清除
        // 调用支付接口
        wx.chooseWXPay({
          timestamp: info.timeStamp, // 支付签名时间戳
          nonceStr: info.nonceStr, // 支付签名随机串
          package: info.package, // 预支付交易会话ID
          signType: info.signType, // 签名方式，默认为'SHA1'，使用 MD5 签名时请注意
          paySign: info.paySign, // 支付签名
          success(res: any) {
            // 支付成功后的回调
            console.log('支付成功', res)
            msg.value = '支付成功！'
            isSubmit.value = true
            // 跳转到支付成功页面
            router.push({ path: '/yunshi/result', query: { oid: route.query.oid } })
          },
          fail(res: any) {
            // 支付失败的回调
            console.log('支付失败', res)
            msg.value = '支付失败，请稍后重试'
            isSubmit.value = true
          },
          complete() {
            isPaying.value = false
          },
        })
      })

      wx.error((res: any) => {
        console.error('微信 SDK 错误:', res)
        msg.value = '微信支付初始化失败'
        isSubmit.value = true
        isPaying.value = false
      })
      // msg.value = '支付成功'
      // isSubmit.value = true
    }
    else if (isMobile.value) {
      window.location.href = info.targetUrl
    }
    else {
      // 非微信浏览器，显示二维码
      qrCodeUrl.value = info.qrCodeBase64
      showQRCodeModal.value = true
    }
  }
  catch (e) {
    console.error('支付异常:', e)
    msg.value = '支付请求失败，请稍后再试'
    isSubmit.value = true
  }
  finally {
    isPaying.value = false
  }
}
// 关闭弹窗
function closeModal() {
  isSubmit.value = false
  showQRCodeModal.value = false
  isPaying.value = false
}
</script>

<template>
  <div class="min-h-screen w-full relative">
    <Header back="/yunshi" />
    <img
      src="/assets/images/yunshi/baogaoye.png"
      alt=""
      class="h-auto w-full object-contain"
    >
    <div class="mx-auto w-full left-0 right-0 top-[3.5%] absolute">
      <div class="text-3xl text-[#60130d] mb-[5%] text-center">
        {{ name }}的八字终生运势报告
      </div>
      <div class="text-xl text-white text-center">
        <div>
          欠缺五行，五行缺*
        </div>
        <div>
          姻缘财富贵荣，尽在终生运势报告
        </div>
      </div>
      <div class="mx-auto mt-[5%] w-[95%] left-0 right-0 relative">
        <div>
          <img
            src="/assets/images/yunshi/border-1.png"
            alt=""
            class="h-auto w-full object-contain"
          >
        </div>
        <div class="mx-auto w-[90%] left-0 right-0 top-[10%] absolute">
          <div class="relative">
            <img
              src="/assets/images/yunshi/title.png"
              alt=""
              class="h-auto w-full object-contain"
            >
          </div>
          <div class="mx-auto w-[90%] left-0 right-0 top-[35%] absolute">
            <div class="relative">
              <img
                src="/assets/images/yunshi/price.png"
                alt=""
                class="h-auto w-full object-contain"
              >
            </div>
            <div class="mx-auto w-[90%] left-0 right-0 top-[40%] absolute">
              <div class="flex items-center justify-around">
                <div class="text-gray-500 line-through">
                  原价：￥{{ price * 4 }}
                </div>
                <div>
                  特惠价：<span class="text-xl text-[#c8492f] font-bold">¥{{ price }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="mx-auto w-[90%] bottom-[5%] left-0 right-0 absolute">
          <div class="flex flex-col gap-3 items-center">
            <div class="pb-3 border-b-1 border-b-gray-500 flex items-center justify-between" @click="submitPayWx">
              <div class="w-[30%]">
                <img
                  src="/assets/images/wx-icon.png"
                  alt=""
                  class="h-auto w-full object-contain"
                >
              </div>
              <div class="w-[30%]">
                <img
                  src="/assets/images/wx-bt.png"
                  alt=""
                  class="h-auto w-full object-contain"
                >
              </div>
            </div>
            <div v-if="!isWeChat()" class="flex items-center justify-between" @click="submitPayZfb">
              <div class="w-[30%]">
                <img
                  src="/assets/images/zfb-icon.png"
                  alt=""
                  class="h-auto w-full object-contain"
                >
              </div>
              <div class="w-[30%]">
                <img
                  src="/assets/images/zfb-bt.png"
                  alt=""
                  class="h-auto w-full object-contain"
                >
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="text-lg text-[#c8492f] mt-[5%] text-center">
        <span>支付成功后，返回当前浏览器查看结果</span>
      </div>
    </div>
    <TipModal
      v-model="isSubmit"
      title="提示"
      :message="msg"
      @close="closeModal"
    />
    <TipModal
      v-model="showQRCodeModal"
      title="提示"
      message="请打开微信扫码支付"
      :image="qrCodeUrl"
      @close="closeModal"
    />
  </div>
</template>
